package com.lnj.orders.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lnj.api.IdGeneratorApi;
import com.lnj.bean.dto.OrdersDTO;
import com.lnj.bean.dto.OrdersItemsDTO;
import com.lnj.bean.model.OrderItems;
import com.lnj.bean.model.Orders;
import com.lnj.orders.mapper.OrdersMapper;
import com.lnj.orders.service.CartService;
import com.lnj.orders.service.OrdersItemsService;
import com.lnj.orders.service.OrdersService;
import com.lnj.orders.utils.OrderListResponse;
import com.lnj.orders.utils.ProductOrderInfo;
import com.lnj.utils.RedisKeys;
import com.lnj.utils.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private IdGeneratorApi idGeneratorApi;

    // 假设你有一个 OrderItemsService 用于操作订单项
    @Autowired
    private OrdersItemsService ordersItemsService;
    @Autowired
    private CartService cartService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    // 订单创建
    @Override
    @Transactional
    public OrdersDTO createOrder(Long userId, OrdersDTO ordersDTO, List<OrdersItemsDTO> orderItemsDTOList, List<Long> cartIds) {
        // 1. 生成订单ID
        ResponseResult rr = idGeneratorApi.getNextId();
        if( rr.getCode()==0){
            throw new RuntimeException("获取id失败");
        }
        // 关键改动：将返回的数据强转为 List<Long> 类型
        Long orderId=Long.parseLong( rr.getData().toString() );


        // 2. 将 DTO 转换为实体类，并设置新生成的ID和时间
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersDTO, orders);
        orders.setId(orderId);
        orders.setOrderStatus(1); // 默认设置为待支付
        orders.setUpdateTime(LocalDateTime.now());
        orders.setUserId(userId);
        // 3. 插入订单主表
        this.save(orders);
        // 4. 处理订单项列表
        if (orderItemsDTOList != null && !orderItemsDTOList.isEmpty()) {
            List<OrderItems> orderItemsList = orderItemsDTOList.stream()
                    .map(itemDTO -> {
                        OrderItems orderItem = new OrderItems();
                        BeanUtils.copyProperties(itemDTO, orderItem);
                        orderItem.setOrderId(orderId);
                        return orderItem;
                    })
                    .collect(Collectors.toList());

            // 调用 OrderItemsService 进行批量插入
            ordersItemsService.saveBatchOrderItems(orderItemsList);
        }

        // 5. 还要删除  cart购物车表中的当前userId的这些被购买的商品的记录
        if (cartIds!=null && !cartIds.isEmpty()&&cartIds.get(0)!=null){
            cartIds.stream().map(cartId -> cartService.deleteCartItem(userId,cartId)).collect(Collectors.toList());
        }

        BeanUtils.copyProperties(  orders, ordersDTO);
        return ordersDTO;
    }

    // 订单详情
    @Override
    public OrdersDTO getOrderById(Long orderId, Long orderStatus) {
        Orders orders = this.getOne(new LambdaQueryWrapper<Orders>()
                .eq(Orders::getId, orderId)
                .eq(Orders::getOrderStatus, orderStatus));
        if (orders == null) {
            throw new RuntimeException("订单不存在或状态不符合");
        }
        OrdersDTO ordersDTO = new OrdersDTO();
        BeanUtils.copyProperties(orders, ordersDTO);
        return ordersDTO;
    }

    @Override
    public Double calculateTotalPrice(Long orderId) {
        // 1. 根据订单ID查询订单详情
        Orders orders = this.getById(orderId);
        if (orders == null) {
            throw new RuntimeException("订单不存在");
        }
        // 2. 查询订单下的所有订单项
        List<OrderItems> orderItemsList = ordersItemsService.list(new LambdaQueryWrapper<OrderItems>().eq(OrderItems::getOrderId, orderId));
        if (orderItemsList == null || orderItemsList.isEmpty()) {
            throw new RuntimeException("订单下没有商品");
        }
        // 3. 计算总金额
        Double totalPrice = 0.0d;
        for (OrderItems orderItem : orderItemsList) {
            totalPrice += orderItem.getPrice() * orderItem.getQuantity();
        }
        return totalPrice;
    }


    /**
     * 根据订单ID查询订单详情
     * @param orderId 订单ID
     * @return 订单详情
     */
    @Override
    public List<ProductOrderInfo> getOrderdetalById(Long orderId) {
        List<ProductOrderInfo> orderItemLists= ordersItemsService.getOrderItemListByOrderID(orderId);
        if(orderItemLists==null || orderItemLists.isEmpty()){
            return null;
        }
        return orderItemLists;
    }

    /**
     * 根据订单ID取消订单
     * @param orderId 订单ID
     * @return 取消结果
     */
    @Override
    public Integer cancelOrder(Long orderId) {
        Orders orders = this.getById(orderId);
        if (orders == null) {
            throw new RuntimeException("订单不存在");
        }
        orders.setOrderStatus(0);
        orders.setUpdateTime(LocalDateTime.now());
        boolean flag=this.updateById(orders);
        if(flag){
            return 1;
        }
        return 0;
    }

    @Override
    public List<OrderListResponse> getOrderList(Long userId, Long orderStatus) {
        List<Orders> orders = null;
        if (orderStatus == 9) {
            orders = this.list(new LambdaQueryWrapper<Orders>()
                    .eq(Orders::getUserId, userId)
                    .orderByDesc(Orders::getId));
        } else {
            orders = this.list(new LambdaQueryWrapper<Orders>()
                    .eq(Orders::getUserId, userId)
                    .eq(Orders::getOrderStatus, orderStatus)
                    .orderByDesc(Orders::getId));
        }
        if (orders == null || orders.isEmpty()) {
            return null;
        }

        // 修复：确保OrderListResponse中的ordersDTO被正确初始化
        List<OrderListResponse> orderListResponses = orders.stream().map(order -> {
            OrderListResponse orderListResponse = new OrderListResponse();
            OrdersDTO ordersDTO = new OrdersDTO(); // 先创建OrdersDTO对象
            BeanUtils.copyProperties(order, ordersDTO); // 复制属性
            orderListResponse.setOrdersDTO(ordersDTO); // 设置到response中
            orderListResponse.setProductOrderInfos(getOrderdetalById(order.getId()));
            return orderListResponse;
        }).collect(Collectors.toList());

        return orderListResponses;
    }

    @Override
    public void updateStatus(Long id, int orderStatus) {
        // 构建更新条件
        LambdaQueryWrapper<Orders> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(Orders::getId, id);
        // 构建更新数据
        Orders updateOrders = new Orders();
        updateOrders.setOrderStatus(orderStatus);
        updateOrders.setUpdateTime(LocalDateTime.now());
        if(orderStatus==2){
            updateOrders.setPaymentType(1);
            updateOrders.setPaymentTime(LocalDateTime.now());
        } else if (orderStatus==3) {
            updateOrders.setShippingTime(LocalDateTime.now());
        }
        this.update(updateOrders, updateWrapper);
    }
}
